<template>
  <el-dialog
    :title="title"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="600px"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="品类" prop="categoryId">
            <el-select v-model="formData.categoryId" placeholder="请选择品类" style="width: 100%" @change="handleCategoryChange">
              <el-option 
                v-for="category in categoryOptions" 
                :key="category.categoryId" 
                :label="category.categoryName" 
                :value="category.categoryId" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入产品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="网络类型" prop="protocolType">
            <el-select v-model="formData.protocolType" placeholder="请选择网络类型" style="width: 100%">
              <el-option 
                v-for="protocol in protocolOptions" 
                :key="protocol.value" 
                :label="protocol.label" 
                :value="protocol.value" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  },
  categoryOptions: {
    type: Array,
    default: () => []
  },
  protocolOptions: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'submit'])

const formRef = ref()

const formData = reactive({
  productId: '',
  categoryId: '',
  categoryName: '',
  name: '',
  protocolType: '',
  remark: ''
})

const rules = {
  categoryId: [
    { required: true, message: '请选择品类', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  protocolType: [
    { required: true, message: '请选择网络类型', trigger: 'change' }
  ]
}

const title = computed(() => {
  return formData.productId ? '编辑产品' : '新增产品'
})

const isEdit = computed(() => {
  return !!formData.productId
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    emit('submit', { ...formData })
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 取消操作
const handleCancel = () => {
  handleClose()
}

// 处理品类选择变化
const handleCategoryChange = (categoryId) => {
  const selectedCategory = props.categoryOptions.find(cat => cat.categoryId === categoryId)
  if (selectedCategory) {
    formData.categoryName = selectedCategory.categoryName
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    productId: '',
    categoryId: undefined,
    categoryName: '',
    name: '',
    protocolType: undefined,
    remark: ''
  })
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  // 清除表单验证状态
  formRef.value?.clearValidate()
  // 只在新增模式下重置表单，编辑模式下保留数据
  if (!isEdit.value) {
    handleReset()
  }
}

// 处理表单数据，将空字符串转换为undefined
const processFormData = (data) => {
  const processed = { ...data }
  Object.keys(processed).forEach(key => {
    if (processed[key] === '') {
      processed[key] = undefined
    }
  })
  return processed
}

// 填充表单数据
const fillFormData = (data) => {
  if (data) {
    const processedData = processFormData(data)
    Object.assign(formData, processedData)
    // 如果是编辑模式且没有categoryName，根据categoryId查找categoryName
    if (formData.categoryId && !formData.categoryName) {
      const selectedCategory = props.categoryOptions.find(cat => cat.categoryId === formData.categoryId)
      if (selectedCategory) {
        formData.categoryName = selectedCategory.categoryName
      }
    }
  }
}

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.data) {
        // 编辑模式：填充数据
        fillFormData(props.data)
      } else {
        // 新增模式：重置表单
        handleReset()
      }
    }
  },
  { immediate: true }
)

// 监听数据变化
watch(
  () => props.data,
  (newData) => {
    if (props.visible && newData) {
      fillFormData(newData)
    }
  },
  { immediate: true, deep: true }
)

</script>

<style scoped>
.icon-uploader .icon {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 4px;
  object-fit: cover;
}

.icon-uploader .icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-uploader .icon-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}
</style>